/*
 * Copyright 2020 edenrun.cn All right reserved. This software is the
 * confidential and proprietary information ofedenrun.cn ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with edenrun.cn.
 */

package com.zoom.pluto.smf.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.http.HttpStatus;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * WebService工具类
 *
 * @author zoom
 * @date 2020-06-09
 */
@Slf4j
public class WebServiceUtils {

    /**
     * 调用webservice方法
     *
     * @param wsdUrl        wsdl地址
     * @param operationName 方法名称
     * @param params        参数列表
     * @return 结果
     * @throws Exception 异常
     */
    public static String callWebService(String wsdUrl, String operationName, String... params) {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        try {
            Client client = dcf.createClient(wsdUrl);
            Object[] objects;
            objects = client.invoke(operationName, params);
            return objects[0].toString();
        } catch(Exception e) {
            log.error("call webservice failed", e);
            return "";
        }
    }

    public static void callWebserviceASMX(String wsdUrl, String operationName, String json) throws Exception {
        try {
            URL url = new URL(wsdUrl);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            byte[] buf = json.getBytes(StandardCharsets.UTF_8);
            // 设置报头
            conn.setRequestProperty("Content-Length", String.valueOf(buf.length));
            conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            conn.setRequestProperty("soapActionString", operationName);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            OutputStream out = conn.getOutputStream();
            out.write(buf);
            out.close();
            // 获取响应状态码
            int code = conn.getResponseCode();
            StringBuffer sb = new StringBuffer();
            if(code == HttpStatus.OK.value()) {
                InputStream is = conn.getInputStream();
                byte[] b = new byte[1024];
                int len = 0;
                while((len = is.read(b)) != - 1) {
                    String s = new String(b, 0, len, StandardCharsets.UTF_8);
                    sb.append(s);
                }
                is.close();
            }
            System.out.println(sb);
        } catch(Exception e) {
            log.error("调用webservice异常", e);
        }
    }

}
